package server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class MainServer {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		InetAddress addressIP = null;
		try {
			addressIP = InetAddress.getLocalHost();
		} catch (UnknownHostException e2) {
			e2.printStackTrace();
		}
		if (System.getSecurityManager() == null) {
	            System.setSecurityManager(new RMISecurityManager());
	    }
		/* Start the classes server */
		int port;
		String classpath = "";
		
		if (args.length != 2) {
			System.out.println("Usage <port> <classpath>");
		}
		port = Integer.parseInt(args[0]);
		classpath = args[1];
				
		try {
		    new ClassFileServer(port, classpath);
		} catch (IOException e) {
		    System.out.println("Unable to start ClassServer: " +
				       e.getMessage());
		    e.printStackTrace();
		}
		// Run the server
		IServer s = null;
		try {
			s = new Server ();
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
		
		while(true) {
	    	   try {
	               LocateRegistry.createRegistry(1099);
	           } catch (RemoteException ex) {
	               //System.err.println("Error creation RMI registry");
	           }
	           try {
	               Registry reg = LocateRegistry.getRegistry(1099);
	               reg.rebind("Server", s);
	    	  // Naming.rebind(""rmi://"+ addressIP.getHostAddress().toString() + ":1099/Server", s);
	    	   System.out.println("Server started on the ip: "+ addressIP.getHostAddress() + ":1099");
	       } catch (Exception e) {
	         System.out.println("Can't rebind: " + e);
	       }
	       try {
	         Thread.sleep(600000); //10 min.
	       } catch (InterruptedException e) {}
	    }
	}
}
